package com.liu.webstore.controller;

import com.liu.webstore.entity.DiscussPost;
import com.liu.webstore.entity.Page;
import com.liu.webstore.enums.StatusEnum;
import com.liu.webstore.service.ElasticsearchService;
import com.liu.webstore.service.LikeService;
import com.liu.webstore.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.IOException;
import java.util.*;

/**
 * @Author LiuYumei
 * @Date 2022/8/21 9:31
 */
@Controller
public class SearchController {
    @Autowired
    private UserService userService;
    @Autowired
    private LikeService likeService;
    @Autowired
    private ElasticsearchService elasticsearchService;

    @GetMapping("/search")
    public String search(String keyword, Page page, Model model) throws IOException {
        // 搜索帖子
        org.springframework.data.domain.Page<DiscussPost> postPage = elasticsearchService.searchDiscussPost(keyword, page.getCurrent() - 1, page.getLimit());
        // 聚合函数
        List<Map<String, Object>> list = new ArrayList<>();
        if (Objects.nonNull(postPage)) {
            for (DiscussPost discussPost : postPage) {
                Map<String, Object> map = new HashMap<>();
                // 帖子
                map.put("post", discussPost);
                // 作者
                map.put("user", userService.getUserById(discussPost.getUserId()));
                // 点赞数量
                map.put("likeCount", likeService.findEntityLikeCount(StatusEnum.ENTITY_TYPE_POST.getStatus(), discussPost.getId()));

                list.add(map);
            }
        }
        model.addAttribute("discussPosts", list);
        model.addAttribute("keyword", keyword);
        // 分页信息
        page.setPath("/search?keyword=" + keyword);
        page.setRows(postPage == null ? 0 : (int) postPage.getTotalElements());
        return "site/search";
    }
}
